package com.kbook.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.kbook.bean.UserBean;
import com.kbook.tool.Tools;

public class ParameterFilter implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest htpReq = (HttpServletRequest) request;
		String userId = request.getParameter("userId");
		
		//TODO 如果是登录用户，则从session里面获取
		request.setAttribute("user", new UserBean(Tools.parseLong(userId), "游客", "游客", 0));
		
		Map<String, String> params = new HashMap<String, String>();
		Enumeration em = request.getParameterNames();
		while (em.hasMoreElements()) {
			String paramName = (String) em.nextElement();
			String valueName = request.getParameter(paramName);
			params.put(paramName, valueName);
		}
		
		//获取用户真实IP
		params.put("ip", (String)htpReq.getHeader("X-Real-IP"));
		//获取用户UA
		params.put("ua", htpReq.getHeader("user-agent"));
		
		request.setAttribute("params", params);
		chain.doFilter(request, response);
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
